﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Meraz.Core.Model;
using Meraz.Core.Repositories;
using Ninject;

namespace Meraz.Core.Commands
{
    public interface ISaveTweetCommand
    {

        ITweetRepository TweetRepository { get; set; }
        ITwitterTagRepository TwitterTagRepository { get; set; }
        ITwitterLinkRepository TwitterLinkRepository { get; set; }
        ITwitterMentionRepository TwitterMentionRepository { get; set; }
        ITwitterUserRepository TwitterUserRepository { get; set; }
        Tweet Execute(Tweet tweet);
    }
    public class SaveTweetCommand : BaseCommand, ISaveTweetCommand
    {
        #region Properties
        [Inject]
        public ITweetRepository TweetRepository { get; set; }

        [Inject]
        public ITwitterTagRepository TwitterTagRepository { get; set; }

        [Inject]
        public ITwitterLinkRepository TwitterLinkRepository { get; set; }

        [Inject]
        public ITwitterMentionRepository TwitterMentionRepository { get; set; }

        [Inject]
        public ITwitterUserRepository TwitterUserRepository { get; set; }
        #endregion

        public Tweet Execute(Tweet tweet)
        {
            if (tweet == null)
                throw new ApplicationException("Cannot save a null object");

            Tweet found = TweetRepository.GetById(tweet.ID);
            if (found == null)
                throw new ApplicationException("Cannot save a new object");

            found.IsClarification = tweet.IsClarification;
            found.IsGeneral = tweet.IsGeneral;
            found.IsLive = tweet.IsLive;
            found.IsQuestion = tweet.IsQuestion;
            found.GenreType = tweet.GenreType;
            found.StatusType = tweet.StatusType;
            Debug.Assert(tweet.Links.Count == found.Links.Count, "Links do not equal in number");
            Debug.Assert(tweet.Mentions.Count == found.Mentions.Count, "Mentions do not equal in number");

            for (int i = 0; i < tweet.Links.Count; i++)
            {
                found.Links[i].ToneType = tweet.Links[i].ToneType;
                found.Links[i].IsInternal = tweet.Links[i].IsInternal;
            }
            for (int i = 0; i < tweet.Mentions.Count; i++)
            {
                found.Mentions[i].IsRetweet = tweet.Mentions[i].IsRetweet;
                found.Mentions[i].IsVia = tweet.Mentions[i].IsVia;
            }

            Commit();
            return found;
        }
    }
}
